package com.example.nio.netty.server;

import com.example.nio.netty.codec.PacketDecoder;
import com.example.nio.netty.codec.PacketEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.net.InetSocketAddress;
import java.util.Date;

public class EchoServer {

    public static void main(String[] args) throws InterruptedException {
        EchoServer server = new EchoServer();
        server.start();
    }

    public void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(group, workerGroup)
            .channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(9999))
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new PacketDecoder());
                    channel.pipeline().addLast(new EchoServerHandler());
                    channel.pipeline().addLast(new MessageRequestHandler());
                    channel.pipeline().addLast(new PacketEncoder());
                }
            });

        bind(serverBootstrap, 9999);
    }

    private static void bind(final ServerBootstrap serverBootstrap, final int port) {
        serverBootstrap.bind(port).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println(new Date() + ": 端口[" + port + "]绑定成功!");
            } else {
                System.err.println("端口[" + port + "]绑定失败!");
            }
        });
    }
}
